#!/bin/bash

WORK_SPACE_PATH=$(pwd)
PARENT_DIR_PATH=$(cd $(dirname $0);pwd)
PROJECT_ROOT=$(dirname $PARENT_DIR_PATH)
SHELL_NAME=$(basename $0)
CONFIG_FILE="$PARENT_DIR_PATH/hooks_config.json"

source "$PARENT_DIR_PATH/common.sh"
# echo $WORK_SPACE_PATH
# echo $PARENT_DIR_PATH
# echo $PROJECT_ROOT
# echo $SHELL_NAME

hook_point=$1

if [ -x "$PARENT_DIR_PATH/tools/jq" ]; then
    jq="$PARENT_DIR_PATH/tools/jq"
elif [ -x $(command -v jq) ]; then
    jq=$(command -v jq)
else
    echo "Not find jq tool."
    exit $EXIT_NOT_FIND_JQ
fi

fun_load_hooks(){
    local config=$(<$CONFIG_FILE)
    local hooks=`echo $config | $jq -r ".$hook_point[]"`
    echo $hooks
}

fun_exec_if_exist(){
    local path="$1/$2.sh"
    if [ -f $path ]; then
        if [ ! -x $path ]; then
            chmod u+x $path
        fi
        #执行hook
        source $path
    else 
        echo "$path isn't existed."
    fi
}

fun_exec_hooks(){
   local hook_name=$1
   case $hook_point in
       'pre_commit')
           fun_exec_if_exist "$PARENT_DIR_PATH/hooks_pre_commit" $hook_name
       ;;
       'prepare_commit_msg')
           fun_exec_if_exist "$PARENT_DIR_PATH/hooks_prepare_commit_msg" $hook_name
       ;;
       'commit_msg')
           fun_exec_if_exist "$PARENT_DIR_PATH/hooks_commit_msg" $hook_name
       ;;
       'post_commit')
           fun_exec_if_exist "$PARENT_DIR_PATH/hooks_post_commit" $hook_name
       ;;
       *)
           echo "unknown hook point: $hook_point"
       ;;
   esac
}


hooks=(`fun_load_hooks`)
if [ ${#hooks[@]} -gt 0 ]; then
    echo "HOOK POINT: $hook_point"
fi
for hook_name in $hooks
do
    echo "HOOKS: $hooks"
    fun_exec_hooks $hook_name        
done